package top.haijunit.work.controller.demo;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.apache.tika.io.TikaInputStream;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.haijunit.work.core.doamin.Result;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 *
 * @author zhanghaijun
 * @since 2024-08-14
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Tag(name = "文件上传")
@ApiSupport(order = 11)
public class FileUploadController {

    @Operation(summary = "文件上传")
    @PostMapping(value = "/upload")
    public Result<Map<String, Object>> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
        return Result.success(getFileInfo(multipartFile));
    }

    @Operation(summary = "文件上传2", parameters = {
        @Parameter(name = "path", description = "上传文件路径", required = true, example = "/default/3/1/bucket/", in = ParameterIn.QUERY)
    })
    @PostMapping(value = "/upload2")
    public Result<Map<String, Object>> uploadFile2(@RequestPart("file") MultipartFile multipartFile, String path) {
        log.info("{}", path);
        return Result.success(getFileInfo(multipartFile));
    }

    private Map<String, Object> getFileInfo(MultipartFile multipartFile) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", IdWorker.getIdStr());
        map.put("originalFilename", multipartFile.getOriginalFilename());
        map.put("contentType", multipartFile.getContentType());
        map.put("size", multipartFile.getSize());
        try {
            map.put("tika", new Tika().detect(TikaInputStream.get(multipartFile.getInputStream())));
        } catch (IOException exception) {
            log.warn("获取文件内容类型失败", exception);
        }
        return map;
    }
}
